﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace ObjectOuster
{
    public enum Music
    {
        Music1,
        Music2,
        Music3,
        Music4,
        Music5,
        Music6
    }
    public class MusicManager:MediaElementManager<Music>
    {
        private Random random = new Random();

        private void MutedChanged(bool isMuted)
        {
            foreach (Music key in Keys)
            {
                this[key].IsMuted=isMuted;
            }
        }
        private void VolumeChanged(double newVolume)
        {
            foreach (Music key in Keys)
            {
                this[key].Volume = newVolume;
            }
        }
        private void MediaEnded(object sender, RoutedEventArgs e)
        {
            Start();
        }
        private void MediaElementAdded(Music theKey, MediaElement theMediaElement)
        {
            theMediaElement.IsMuted = Muted;
            theMediaElement.Volume = Volume;
            theMediaElement.MediaEnded += MediaEnded;
            if (Keys.Count == 6)
            {
                Start();
            }

        }
        private void MediaElementChanged(Music theKey, MediaElement theOldMediaElement, MediaElement theNewMediaElement)
        {
            theOldMediaElement.Stop();
            theOldMediaElement.MediaEnded -= MediaEnded;
            theNewMediaElement.IsMuted = Muted;
            theNewMediaElement.Volume = Volume;
            theNewMediaElement.MediaEnded += MediaEnded;
        }
        public void Start()
        {
            int number = random.Next(Keys.Count);
            foreach (Music key in Keys)
            {
                if (number == 0)
                {
                    Play(key);
                    return;
                }
                number--;
            }
        }
        public MusicManager():base(0.25,false)
        {
            OnMutedChanged += MutedChanged;
            OnVolumeChanged += VolumeChanged;
            OnMediaElementAdded += MediaElementAdded;
            OnMediaElementChanged += MediaElementChanged;
        }
    }
}
